var $table = $("#table_concept");
var $search=$("#search_button");

$(document).ready(function () {
    $.jgrid.defaults.styleUI = 'Bootstrap';
    $table.jqGrid({
        datatype: "json",
        mtype: "post",       //ajax提交方式。POST或者GET，默认GET
        url: "/concept/index/data", //获取数据的地址
        height: 350,
        autowidth: true,
        shrinkToFit: true,  //此属性用来说明当初始化列宽度时候的计算类型，如果为ture，则按比例初始化列宽度。如果为false，则列宽度使用colModel指定的宽度
        rowNum: 10,
        rowList: [10, 20, 30],
        loadonce:true,      //如果为ture则数据只从服务器端抓取一次，//一次性加载所有数据，用于前端分页
        colNames: ['序号', '名称',  '父序号','操作'],
        colModel: [
            {name: 'conceptId', index: 'conceptId', editable: true, width: 60, sorttype: "int", search: true},
            {name: 'variaName', index: 'variaName', editable: true, width: 100},
            {name: 'parentId', index: 'parentId', editable: true, width: 100, sortable: false},
            {name: '操作', label: '操作',width: 40,
                formatter:
                    function(cellvalue, options, row){
                        return"<a style='margin:2px' class=\'btn btn-primary btn-sm \' href=\'#\' title=\'编辑\'>" +
                            "<i class=\"fa fa-edit\">" +
                            "</i>" +
                            "</a>" +
                            "<a style='margin:2px' class=\"btn btn-danger btn-sm \" href=\"#\" title=\"删除\">" +
                            "<i class=\"fa fa-remove\">" +
                            "</i>" +
                            "</a>"
                    }
            }
        ],
        pager: "#pager_concept",
        viewrecords: true,
        caption: "表1",
        hidegrid: false,
        multiselect: true,//复选框
        multiboxonly: true,
        toolbar: [true, "top"]//在点击表格row时只支持单选，只有当点击checkbox时才多选，需要multiselect=true是有效
    }).navGrid('#pager_concept',{edit:false,add:false,del:false,search:false,refresh:false},{height:200});
    $("#t_table_concept").append(
        "<div class=\"input-group\" style=\"float: left;width:240px;margin:0 2px\">\n" +
        "<input id=\"find_conceptid\" name=\"find_conceptid\" type=\"text\" class=\"form-control\"/>\n" +
        "<span class=\"input-group-btn\">\n" +
        "<button class=\"btn btn-success\" type=\"button\" onclick=\"layer.msg('未实现')\"><i aria-hidden=\"true\" class=\"fa fa-search\"></i>查询</button>\n" +
        "</span>\n" +
        "</div>" +
        "<div style=\"float:right;margin:0 2px\">" +
        "<button id=\"add\" type=\"button\" class=\"btn btn-warning\" onclick=\"addDlg()\"><i aria-hidden=\"true\" class=\"fa fa-plus\"></i>增加</button>"+
        "</div>" +
        "<div style=\"float:right;margin:0 2px\">" +
        "<button id=\"delete\" type=\"button\" class=\"btn btn-danger\" onclick=\"layer.msg('有点问题')\"><i aria-hidden=\"true\" class=\"fa fa-trash\"></i>删除</button>" +
        "</div>" +
        // "<div style=\"float:right;margin:0 2px\">" +
        // "<button id=\"edit\" type=\"button\" class=\"btn btn-warning\" onclick=\"editDlg()\"><i aria-hidden=\"true\" class=\"fa fa-edit\"></i>修改</button>" +
        // "</div>" +
        "<div style=\"float:right;margin:0 2px\">" +
        "<button id=\"refresh\" type=\"button\" class=\"btn btn-info\" onclick=\"refDlg()\"><i aria-hidden=\"true\" class=\"fa fa-refresh\"></i>刷新</button>" +
        "</div>"
    );
//
    $(window).bind('resize', function () {
        var width = $('.jqGrid_wrapper').width();
        $('#table_list_2').setGridWidth(width);
    });
});
function addDlg() {
    $("#addDlg").modal();
    $.ajax({
        url:"/concept/index/maxid",
        type:"post",
        contentType: "application/json;charset=utf-8",
        success:function (data) {
            $('#addconceptId').val(data+1);
        }
    });
}
function save(modal) {
    var form_data=$(modal).serialize();
    var b_data= decodeURIComponent(form_data,true);//防止中文乱码
    var userdata=DataDeal.formToJson(b_data);//转化为json
    $.ajax({
        type: "POST",
        url: "/concept/index/add",
        contentType: "application/json;charset=utf-8",
        data: userdata,
        success: function (data) {
            // alert(data);
            layer.msg(data);
            reload();
            $('#addDlg').modal('hide').on("hidden", function () {
                $(this).removeData("modal");
            });
            document.getElementById("form_add").reset();//重置表单
        },
        error: function (XMLHttpRequest) {
            alert("Error");
        }
    });
}

function validateAdd() {
    return $("#form_add").validate({
        rules: {
            conceptId: {
                required: true,
                digits: true
            },
            variaName: {
                required: true
            },
            parentId: {
                digits: true
            }
        },
        messages: {
            conceptId: {
                required: "请输入Id",
                digits: "Id必须是整数！"
            },
            variaName: {
                required: "请输入名称！"
            },
            parentId: {
                required: "Id必须是整数！"
            }
        }
    });
}
$("#add_button").click(function() {
    if(validateAdd().form())
        save($("#form_add"));
});


//*************************************************************************************
function editDlg() {
    var rowIds =  $table.jqGrid('getGridParam', 'selarrrow');
    if(rowIds.length===1) {
        $("#editDlg").modal();
        var rowid =  $table.getGridParam("selrow");
        var row =  $table.jqGrid('getRowData', rowid);
        $('#editconceptId').val(row.conceptId).attr('readonly', true);
        $('#editvariaName').val(row.variaName);
        $('#editparentId').val(row.parentId);
    }
    else layer.msg("请选择一行进行编辑！");
}

function update() {
    var form_data = $('#form_edit').serialize();
    var b_data = decodeURIComponent(form_data,true);//防止中文乱码
    var userdata = DataDeal.formToJson(b_data);//转化为json
    $.ajax({
        type: "post",
        url: "/concept/index/update",
        contentType: "application/json;charset=utf-8",
        data: userdata,
        // async: false,//设置为同步传输
        success: function (msg) {
            layer.msg(msg);
            reload();
            $('#editDlg').modal('hide').on("hidden", function () {
                $(this).removeData("modal");
            });
            document.getElementById("form_edit").reset();//重置表单
        }
    });
}
//表单验证
function validateEdit() {
    return $("#form_edit").validate({
        rules: {
            variaName: {
                required: true
            },
            parentId: {
                digits: true
            }
        },
        messages: {
            variaName: {
                required: "请输入名称！"
            },
            parentId: {
                required: "parentId必须是整数！"
            }
        }
    })
}
$("#update_button").click(function() {
    if (validateEdit().form())
        update();
});
//**************************************************************************************
function delDlg(){
    var rowIds = $table.jqGrid("getGridParam", "selarrrow");
    console.log(rowIds);
    layer.confirm("确认要删除选中的数据吗?", {
            btn : [ '确定', '取消' ]},
        function () {
            for(var i=0;i<rowIds.length;i++) {
                var rowid = rowIds[i];
                var row = $table.jqGrid('getRowData', rowid);
                var id = row.conceptId;
                $.ajax({
                    type: "post",
                    url: "/concept/index/delete",
                    data: {"id": id},
                    dataType: "text",
                    success: function () {
                        reload();
                        layer.closeAll('dialog');
                    }
                });
            }
        }
    );
}
//************************查找******************************************************
function serDlg() {
    $("#searchDlg").modal();
    document.getElementById("search_input").value="";
}
//对dialog上的form进行表单验证
function validateSearchConceptId() {
    return $("#form_search").validate({
        rules: {
            search_input: {
                digits: true
            }
        },
        messages: {
            search_input: {
                digits: "id必须是整数！"
            }
        }
    });
}
function validateSearchParentId() {
    return $("#form_search").validate({
        rules: {
            search_input: {
                digits: true
            }
        },
        messages: {
            search_input: {
                digits: "ParentId必须是整数！"
            }
        }
    });
}
$search.click(function () {
    var value = $("#search_select ").val();//获取id为search_select的元素的值
    console.info(value);

    if(value==="conceptId") {

        if(validateSearchConceptId().form()) {
            SearchConceptId();
        }
    } else if(value==="variaName"){
        searchVariaName();
    } else if(value==="parentId"){

        if(validateSearchParentId().form()) {
            searchParentId();
        }
    }
});
function SearchConceptId() {
    var id = $("#search_input").val().replace(/(^\s*)|(\s*$)/g, "");//replace用于去掉首尾的空格
    console.info(id);
    if(id!==null&&id!==undefined&&id!=="") {
        $('#searchDlg').modal('hide').on("hidden", function () {
            $(this).removeData("modal");
        });
        $table.jqGrid('clearGridData');
        $table.jqGrid('setGridParam', {  // 重新加载数据
            url: "/concept/index/find/conceptid",
            datatype: 'json',
            mtype: "post",
            postData: {"id": id}
        }).trigger("reloadGrid");
    }
    else {
        $("#searchDlg").modal('hide').on("hidden", function () {
            $(this).removeData("modal");
        });
    }
}
function searchVariaName() {
    var id = $("#search_input").val().replace(/(^\s*)|(\s*$)/g, "");//replace用于去掉首尾的空格
    if(id!==null&&id!==undefined&&id!=="") {
        $('#searchDlg').modal('hide').on("hidden", function () {
            $(this).removeData("modal");
        });
        $table.jqGrid('clearGridData');
        $table.jqGrid('setGridParam', {  // 重新加载数据
            url: "/concept/index/find/varianame",
            datatype: 'json',
            mtype: "post",
            postData: {"name": id}
        }).trigger("reloadGrid");
    }
    else {
        $("#searchDlg").modal('hide').on("hidden", function () {
            $(this).removeData("modal");
        });
    }
}
function searchParentId() {
    var id = $("#search_input").val().replace(/(^\s*)|(\s*$)/g, "");//replace用于去掉首尾的空格
    if(id!==null&&id!==undefined&&id!=="") {
        $('#searchDlg').modal('hide').on("hidden", function () {
            $(this).removeData("modal");
        });
        $table.jqGrid('clearGridData');
        $table.jqGrid('setGridParam', {  // 重新加载数据
            url: "/concept/index/find/parentid",
            datatype: 'json',
            mtype: "post",
            postData: {"parentid": id}
        }).trigger("reloadGrid");
    }
    else {
        $("#searchDlg").modal('hide').on("hidden", function () {
            $(this).removeData("modal");
        });
    }
}
//******************************************************************************
function refDlg() {
    reload();
}
function reload() {
    $table.jqGrid('clearGridData');
    $table.jqGrid('setGridParam',{  // 重新加载数据
        datatype:'json',
        mtype:"post",
        url:"/concept/index/data"
    }).trigger("reloadGrid");
}




